<?php
declare (strict_types=1);

namespace app\common\service;

use app\common\model\SysConfModel;
use think\facade\Cache;

//系统配置
class SysConfService
{
    /*
     * @title 获取配置缓存
     * @param string $key
     * @return string
     * */
    public function getKey(string $key): string
    {
        $common_key = config('app.sys_conf_key');
        $result = Cache::store('redis')->get($common_key . $key);
        if ($result !== false) return '';

        $data = SysConfModel::where('key', '=', $key)->find();
        if (empty($data)) {
            return '';
        }
        $this->setKey($key, $data->getAttr('value'), $data->getAttr('type'));
        if (2 == $data->getAttr('type')) {
            return json_decode($data->getAttr('value'), true);
        }
        return $data->getAttr('value');
    }

    /*
     * @title 设置配置缓存
     * @param string $key 缓存的key
     * @param string $value 缓存的val
     * @param int $type 值的类型1字符串2json
     * @return bool
     * */
    public function setKey(string $key, string $value, int $type): bool
    {
        $common_key = config('app.sys_conf_key');
        if ($type == 2) {
            Cache::store('redis')->set($common_key . $key, json_decode($value, true), 0);
        } else {
            Cache::store('redis')->set($common_key . $key, $value, 0);
        }
        return true;
    }

}
